import sys
import time
import logging
import argparse
import traceback


# Initialize logger
logger = logging.getLogger(__name__)


class Dummy:
    def __call__(self):
        logger.debug('Dummy() __call__()')
        return self


'''
def loop_process(rob):
    #True - do nothing
    #False - break
    return True


def user_command(rob, cmd):
    #False - not defined cmd
    return False
'''


def main(rob, process_loop=None, process_command=None):
    """Main function to control the program."""
    # Parse command-line arguments
    parser = argparse.ArgumentParser(description='Debug mode control')
    parser.add_argument('-n', '--no-debug', action='store_true', help='Disable debug mode')
    parser.add_argument('--log-level', default='DEBUG', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Set the logging level')
    args = parser.parse_args()

    main_loop(rob, process_loop, process_command, args.no_debug, args.log_level)


def main_loop(rob, process_loop=None, process_command=None, no_debug=False, log_level='DEBUG'):
    # Configure logging
    logging.basicConfig(
        level=getattr(logging, log_level),
        format='%(asctime)s[%(levelno)s|%(threadName)s|%(lineno)d] %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )

    # Initialize Demo instance
    if not rob():
        logger.error('rob __call__ failed.')
        sys.exit(1)

    try:
        while True:
            if process_loop:
                if not process_loop(rob): break

            if no_debug:
                logger.debug('Sleeping for 600 seconds...')
                time.sleep(600)
                continue

            cmd = input('> ')
            if cmd in ('exit', 'quit'):
                break

            if process_command is not None:
                if process_command(rob, cmd): continue

            try:
                # Common command, use eval (not recommended for production)
                ob = eval(cmd)
                print(vars(ob).keys() if hasattr(ob, '__dict__') else ob)
            except Exception as e:
                traceback.print_exc()
                print(f'Unknown cmd: {cmd}')


    except KeyboardInterrupt:
        logger.info('get KeyboardInterrupt - ')
    except Exception as e:
        logger.error(f'An error occurred: {e}', exc_info=True)
    finally:
        logger.info('Exiting...')


if __name__ == '__main__':
    main(Dummy())

